package toledo.post;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;

import toledo.rest.User;
import toledo.util.TwitterSearch;

public class AddUserServlet extends HttpServlet
{
	private static final long serialVersionUID=1L;
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		String username = req.getParameter(User.USERNAME);
		String password = req.getParameter(User.PASSWORD);
		String twitter_id = req.getParameter(User.TWITTER_ID);
		Entity e = new Entity(User.DATABASE);
		e.setProperty(User.USERNAME,username);
		e.setProperty(User.PASSWORD,password);
		e.setProperty(User.TWITTER_ID,twitter_id);
		
		TwitterSearch ts = new TwitterSearch();
		JSONObject tinfo = ts.getUserinfoFromTwitterID(twitter_id);

		try
		{
			e.setProperty(User.FULLNAME,tinfo.getString("name"));
			e.setProperty(User.PIC_URL,tinfo.getString("profile_image_url").replace("_normal.jpg","_bigger.jpg"));
			DatastoreServiceFactory.getDatastoreService().put(e);
		}
		catch(JSONException e1)
		{
		}
		
		resp.sendRedirect("database.jsp");
	 }
}